<template>
	<div>
		<div style="padding: 5px;margin-bottom: 5px;display: flex;justify-content: flex-start;align-items: center;">
			<div>
				<el-dropdown split-button type="primary" :disabled="data?.type=='form' || data?.type=='table'">
				      新增
				      <template #dropdown>
				        <el-dropdown-menu>
				          <el-dropdown-item v-if="(data?.type!='form' || data?.type!='table')"  @click.stop="addFolder">新增根目录</el-dropdown-item>
						  <el-dropdown-item v-if="(formData.id && formData.type=='folder')" @click.stop="addFolder">新增子目录</el-dropdown-item>
						  <el-dropdown-item v-if="data?.type=='folder'" :disabled="disabled" @click.stop="addFormRule">新增表单规则</el-dropdown-item>
				          <el-dropdown-item v-if="data?.type=='folder'" :disabled="disabled" @click.stop="addTableRule">新增表格规则</el-dropdown-item>
				        </el-dropdown-menu>
				      </template>
				</el-dropdown>
			</div>
			
			<el-divider direction="vertical" />
			
			<div>
				<el-button type="primary" :disabled="disabled" @click.stop="saveForm" :loading="loading">保存</el-button>
			</div>
			
			<el-divider direction="vertical" />
			
			<div>
				<el-button type="danger" :disabled="(!formData.id)" @click.stop="deleteRow" :loading="loading">
					删除
				</el-button>
			</div>
			
<!-- 			<div style="margin-left: 8px;">
				<el-button type="warning" :disabled="(!formData.id)" @click.stop="deleteRow">
					<i class="iconfont-sys">&#xe65e;</i>
					撤销	
				</el-button>
			</div> -->
			
		</div>
		<div class="folder-pane">
			<div class="head">
				<span>{{formData.name +" " }}{{data?.type!='form' && data?.type!='table' ? '目录':'规则'}}信息</span>
			</div>
			<div class="body">
				<ElForm ref="formRef" :model="formData" :rules="fieldRules" label-width="135px">
				  <ElFormItem label="规则名称" prop="name">
				    <ElInput v-model="formData.name" :disabled="disabled" />
				  </ElFormItem>
				  
				  <ElFormItem label="规则标识" prop="code">
				    <ElInput v-model="formData.code" :disabled="disabled" />
				  </ElFormItem>
				  
				  <ElFormItem label="是否启用" prop="enabled">
				    <ElSelect v-model="formData.enabled" :disabled="disabled">
				      <ElOption label="启用" value="0" />
				      <ElOption label="禁用" value="1" />
				    </ElSelect>
				  </ElFormItem>
				  
				  <ElFormItem label="是否分页" prop="pagination" v-if="data?.type=='table'">
				    <ElSelect v-model="formData.pagination" >
				      <ElOption label="是" value="0" />
				      <ElOption label="否" value="1" />
				    </ElSelect>
				  </ElFormItem>
				  
				  <ElFormItem label="规则备注" prop="remark" >
				    <ElInput v-model="formData.remark" type="textarea" :rows="5" :disabled="disabled"/>
				  </ElFormItem>
				
				  <ElFormItem label="规则排序" prop="sort" >
				    <ElInputNumber
				      v-model="formData.sort"
				      :min="0"
				      controls-position="right"
					  :disabled="disabled"
				    />
				  </ElFormItem>
				</ElForm>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
	import { h, ref, reactive, onMounted, nextTick } from 'vue'
	import { ElDialog, FormInstance, ElTag } from 'element-plus'
	import { ElMessageBox, ElMessage } from 'element-plus'
	import type { FormRules } from 'element-plus'
	import { useCheckedColumns } from '@/composables/useCheckedColumns'
	import ArtButtonTable from '@/components/core/forms/ArtButtonTable.vue'
	import { DataSourceService } from '@/api/sys/dataSourceApi'
	import { SearchChangeParams, SearchFormItem } from '@/types'
	import { useCommon } from '@/composables/useCommon'
	import { useWindowSize } from '@vueuse/core'
	import { RuleService } from '@/api/data-rule/ruleApi'
	import { watch } from 'vue-demi'
	const emits = defineEmits(['refresh-tree'])
  const data=ref<any>();
  const props=defineProps({
  	data: {
  		type: Object,
  		default: () => {}
  	},
  })
  const { containerMinHeight } = useCommon()
  const { width } = useWindowSize()
  defineOptions({ name: 'FolderForm' })
  
  const formRef = ref<FormInstance>()
  const loading = ref(false)
  const disabled = ref(true)
  
  //表单字段
  const formData = ref<any>({
    id: '',
  	parentId:'',
    name: '',
    code: '',
    type: 'folder',
    enabled: '0',
	pagination:'0',
    sort: 0,
  	remark:''
  })
  
  // 验证规则
  const fieldRules = reactive<FormRules>({
    name: [
      { required: true, message: '请输入规则名称', trigger: 'blur' },
      { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    code: [
      { required: true, message: '请输入规则标识', trigger: 'blur' }
    ],
    type: [
      { required: true, message: '请选择规则类型', trigger: 'change' }
    ],
	remark: [
	  { min: 0, max: 50, message: '长度在 0 到 250 个字符', trigger: 'blur' }
	],
  })
  
  //添加目录
  const addFolder=()=>{
	  disabled.value=false;
	  if(data.value?.id){
		  editRow('add','folder',data.value?.id)
	  }else{
		  editRow('add','folder','-1')
	  }
  }
  
  const addFormRule=()=>{
  	  disabled.value=false;
  	  editRow('add','form',data.value?.id)
  }
  
  const addTableRule=()=>{
  	  disabled.value=false;
  	  editRow('add','table',data.value?.id)
  }
  
  const editRow=(oprType:string,type:string,parentId:string,row?:any)=>{
	  formData.value.id=row?.id || '';
	  formData.value.parentId=row?.parentId || parentId;
	  formData.value.name=row?.name || '';
	  formData.value.code=row?.code || '';
	  formData.value.type=row?.type || type;
	  formData.value.enabled=row?.enabled || '0';
	  formData.value.pagination=row?.pagination || '0';
	  formData.value.sort=row?.sort || 1;
	  formData.value.remark=row?.remark || ''
	  disabled.value=false;
  }
  
  const saveForm = async () => {
	  
    if (!formRef.value) return
    await formRef.value.validate(async (valid) => {
      if (valid) {
        try {
			loading.value = true
  			const data = await RuleService.save(formData.value);
  			formData.value.id=data.id;
			emits('refresh-tree', formData)
  			ElMessage.success(`成功`)
        } catch {
  			ElMessage.error(`失败`)
        }finally{
			loading.value = false
		}
      }
    })
  }
  
  const deleteRow = async () => {
    try {
		if(!formData.value.id){
			ElMessage.warning("无可以删除的数据.");
			return;
		}
      await ElMessageBox.confirm('确定要删除该'+formData.value.name+'及其包含的所有信息吗？删除后无法恢复', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
  		loading.value = true
  		try {
  			await RuleService.delete(formData.value.id);
  			emits('refresh-tree', formData.value);
			ElMessage.success('删除成功')
			formData.value.id='';
			formData.value.parentId='-1';
			formData.value.name='';
			formData.value.code='';
			formData.value.type='folder';
			formData.value.enabled='0';
			formData.value.sort=1;
			formData.value.remark=''
			disabled.value=true;
  		} catch {
  			ElMessage.error(`失败`)
  		}finally{
  			loading.value = false
  		}
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('删除失败')
      }
    }
  }
  
  watch(props,() => {
  		data.value=props.data
		if(data.value){
			editRow('edit',data.value.type,data.value.parentId,data.value);
		}
  	},
      { immediate: true, deep: true },
  )
  onMounted(() => {
  })
</script>

<style lang="scss" scoped>
	.folder-pane{
		border: 1px solid var(--art-card-border);
		.head{
			height: 2.1875rem;
			border-bottom: 1px solid var(--art-card-border);
			display: flex;display: flex;
			justify-content: flex-start;
			align-items: center;
			padding-left: 0.5rem;
		}
		.body{
			padding: 0.5rem;
		}
		
	}
</style>